/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.baseDataView;
/**
 * 说明：
 * 仓库管理
 * @Author：黄盛强
 * @Date：2012-03-20
 */
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.table.TableRowSorter;

import com.ruipengkj.bean.TStock;
import com.ruipengkj.bean.TStockInOut;
import com.ruipengkj.bean.TStore;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.base.query.PageIndex;
import com.ruipengkj.commons.base.query.PageModel;
import com.ruipengkj.commons.base.query.PageView;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonRoundBlue;
import com.ruipengkj.component.RPJButtonRoundGray;
import com.ruipengkj.component.RPJButtonRoundOrager;
import com.ruipengkj.component.jpanel.QueryPanel;
import com.ruipengkj.component.page.PageDelegale;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.DataStorageModel;
import com.ruipengkj.service.TStockInOutService;
import com.ruipengkj.service.TStockService;
import com.ruipengkj.service.TStoreService;
import com.ruipengkj.view.base.BasePagePanel;

public class DataStoragePanel extends BasePagePanel<TStore> implements PageDelegale ,Runnable{

	private static final long serialVersionUID = 1L;
	
	private JLabelJTextFieldComponent storageID; //仓库编号
	private JLabelJTextFieldComponent storageName; //仓库名称
	private JButton queryButton; //查询
	private JButton addButton; //增加仓库
	private JButton updateButton; //修改仓库
	private JButton delButton; //删除仓库
	
	private JTable table;
	private JScrollPane tableJsp;
	private DataStorageModel dataStorageModel;
	
	private PagingComponent pagingComponent;//翻页组件
	private PageView<TStore> pageView;//翻页主键
	private TStoreService storeService;//仓库操作对象
	private DataStorageAddOrModifyDialog dataStorageAddOrModifyDialog;//添加或修改仓库对话框
	
	public DataStoragePanel() {
		setLayout(new BorderLayout());
		init();
		initListener();
		storeService=BuildSpringApplication.getInstance().getTStoreServiceImpl();
	}
	
	private JPanel initTop() {
		QueryPanel queryPanel=new QueryPanel("仓库管理",ImageFactory.loadImage(ImageFactory.FUN_3_ICON_3));
		JPanel top_panel = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		
		storageID = new JLabelJTextFieldComponent("仓库编号：", 20);
		storageName= new JLabelJTextFieldComponent("仓库名称：", 20);
		queryButton = new RPJButtonBlue("查询");
		
		top_panel.add(storageID);
		top_panel.add(storageName);
		top_panel.add(queryButton);
		queryPanel.addPanel(top_panel);
//		queryPanel.addBoxPanel(top_panel);
		return queryPanel;
	}
	
	private void init() {
		pageView = new PageView<TStore>();
		dataStorageModel = new DataStorageModel();
		table=uiFactory.createRPJTable(dataStorageModel, null, this, 30, JLabel.CENTER);
		tableJsp=uiFactory.createJScrollPane(table);
		pagingComponent=new PagingComponent();
		pagingComponent.setPageDelegale(this);
		
		JPanel gardPanel=uiFactory.createGridJPanel(1, 2);
		JPanel jp1=uiFactory.createFlowJPanel(FlowLayout.LEFT);
		addButton = new RPJButtonRoundBlue("添加(Ctrl+A)");
		updateButton = new RPJButtonRoundGray("修改(Ctrl+M)");
		delButton = new RPJButtonRoundOrager("删除(Ctrl+D)");
		jp1.add(new JLabel("   "));
		jp1.add(addButton);
		jp1.add(updateButton);
		jp1.add(delButton);
		gardPanel.add(jp1);
		gardPanel.add(pagingComponent);
		
		this.add(initTop(),BorderLayout.NORTH);
		this.add(tableJsp,BorderLayout.CENTER);
		this.add(gardPanel,BorderLayout.SOUTH);
		//排序
		TableRowSorter<DataStorageModel> tableRowSorter = new TableRowSorter<DataStorageModel>(dataStorageModel);  
		table.setRowSorter(tableRowSorter);
	}
	
	//初始化监听器
	private void initListener() {
		storageID.getText().addKeyListener(this);
		storageName.getText().addKeyListener(this);
		queryButton.addActionListener(this);
		addButton.addActionListener(this);
		addButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		updateButton.addActionListener(this);
		updateButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_M, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		delButton.addActionListener(this);
		delButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_D, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
	}
	
	@Override
	public void run() {
		this.termQuery(1);
	}
	
	//条件查询
	@Override
	protected void termQuery(final int currentPage){
		final TStore tstore=new TStore();
		tstore.setStoreID(storageID.getText().getText().trim());
		tstore.setName(storageName.getText().getText().trim());
		new Thread(){
			public void run(){
				tableJsp.getViewport().remove(table);
				tableJsp.getViewport().add(waitComponent);
				try {
					pageView.setCurrentPage(currentPage);
					PageModel<TStore> pageModel = storeService.getScrollService(pageView.getFirstResult(), pageView.getMaxResult(),tstore);
					pageView.setPageModel(pageModel);
					pageView.setPageIndex(PageIndex.getPageIndex(pageView.getPageCode(), pageView.getCurrentPage(), pageView.getTotalPage()));
					if(pageModel!=null){
						TabelUtil.clearTableRowSorter(table);
						dataStorageModel.setRowData(pageModel.getResultList());
						SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
								tableJsp.getViewport().remove(waitComponent);
								tableJsp.getViewport().add(table);
								TabelUtil.setJTabelAutoClumnWidth(table);
								pagingComponent.show();
							}
						});
					}else{
						//没有订单数据
						tableJsp.getViewport().remove(waitComponent);
						tableJsp.getViewport().add(table);
						dataStorageModel.clear();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	@Override
	protected PageView<TStore> getPageView() {
		return this.pageView;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==queryButton){
			//查询按钮
			this.termQuery(1);
		}else if(e.getSource()==addButton){
			//添加按钮
			dataStorageAddOrModifyDialog = new DataStorageAddOrModifyDialog(null,"添加仓库",true);
			dataStorageAddOrModifyDialog.showDialog(null);
			if(dataStorageAddOrModifyDialog.isSuccess){
				this.termQuery(1);
			}
		}else if(e.getSource()==updateButton){
			//修改按钮
			this.modifyStore();
		}else if(e.getSource()==delButton){
			//删除按钮
			this.deleteStore();
		}
	}
	@Override
	public void keyReleased(KeyEvent e) {
		if(e.getSource()==table){
			if(e.getKeyCode()==KeyEvent.VK_DELETE){
				//删除按钮
				this.deleteStore();
			}
		}else if(e.getSource()==storageID.getText()||e.getSource()==storageName.getText()){
			//查询
			if(e.getKeyCode()==KeyEvent.VK_ENTER){
				queryButton.doClick();
			}
		}
	}
	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getSource()==table){
			if(table.getSelectedRowCount()!=0){
				if(e.getClickCount() == 2){
	    			//修改仓库
	    			this.modifyStore();
	    		}
			}
		}
	}
	
	//修改仓库
	private void modifyStore(){
		if(table.getRowCount()!=0){
			int row=table.getSelectedRow();
			if(row!=-1){
				String storeID=(String)table.getValueAt(row, 0);
				try {
					TStore tStore=storeService.getByIdService(storeID);
					dataStorageAddOrModifyDialog = new DataStorageAddOrModifyDialog(null,"修改仓库",true);
					dataStorageAddOrModifyDialog.showDialog(tStore);
					if(dataStorageAddOrModifyDialog.isSuccess){
						this.termQuery(1);
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}else{
				JOptionPane.showMessageDialog(null,"请选择行在进行修改");
				return;
			}
		}
	}
	 //删除仓库
	private void deleteStore(){
		if(table.getRowCount()!=0){
			int row=table.getSelectedRow();
			if(row!=-1){
				if(JOptionPane.showConfirmDialog(null, "是否要删除选择记录！（如有其他表数据使用此仓库，将清除此数据的仓库）")==0){
					String storeID=(String)table.getValueAt(row, 0);
					try {
						TStore tStore = new TStore(storeID);
						//清除使用此仓库的库存表，中的仓库数据。否则存在外键不能删除
						TStockService tStockService = BuildSpringApplication.getInstance().getTStockServiceImpl();
						List<TStock> tStockList = tStockService.findService(new TStock(tStore));
						if(tStockList != null) {
							for (int i = tStockList.size()-1; i >= 0; --i) {
								tStockList.get(i).setTStore(null);
								tStockService.modifyService(tStockList.get(i));
							}
						}
						//清除使用此仓库的入出库表，中的仓库数据。否则存在外键不能删除
						TStockInOutService tStockInOutsService = BuildSpringApplication.getInstance().getTStockInOutServiceImpl();
						List<TStockInOut> tStockInOutList = tStockInOutsService.findService(new TStockInOut(tStore));
						if(tStockInOutList != null) {
							for (int i = tStockInOutList.size()-1; i >= 0; --i) {
								tStockInOutList.get(i).setTStore(null);
								tStockInOutsService.modifyService(tStockInOutList.get(i));
							}
						}
						
						storeService.deleteService(storeID);
						JOptionPane.showMessageDialog(null, "删除成功!");
						this.termQuery(1);
					} catch (Exception e1) {
						JOptionPane.showMessageDialog(null, "删除失败！");
						e1.printStackTrace();
					}
				}
			}else{
				JOptionPane.showMessageDialog(null,"请选择行在进行删除");
				return;
			}
		}
	}

	@Override
	public void clear() {
		dataStorageModel.clear();
		storageID.getText().setText(""); //仓库编号
		storageName.getText().setText(""); //仓库名称
	}
	
}
